package com.tangyuan.niochat.client;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Date;

import com.tangyuan.niochat.protocol.PacketCode;
import com.tangyuan.niochat.protocol.request.LoginRequestPacket;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * Created on 2019-08-28
 *
 * @author fenghongyu
 */
public class ChatClientHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        System.out.println(new Date() + ": 客户端写出数据");
        // 1. 获取数据
        LoginRequestPacket loginRequestPacket = new LoginRequestPacket();
        loginRequestPacket.setUserId(2103797);
        loginRequestPacket.setPassWord("pwd");
        // 2. 写数据
        ctx.channel().writeAndFlush(PacketCode.INSTANCE.encode(ctx.alloc(), loginRequestPacket));
    }

    private ByteBuf getByteBuf(ChannelHandlerContext ctx) {
        ByteBuf byteBuf = null;
        try {
            while (true) {
                // 1. 获取二进制抽象 ByteBuf
                byteBuf = ctx.alloc().buffer();
                // 2. 准备数据,等待用户在控制台输入，指定字符串的字符集为 utf-8
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
                // 3. 填充数据到 ByteBuf
                String msg = new Date() + bufferedReader.readLine() + "\n";
                ByteBuf out = byteBuf.writeBytes(msg.getBytes());
                ctx.channel().writeAndFlush(out);
                return byteBuf;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return byteBuf;
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf) msg;
        System.out.println(new Date() + "客户端收到服务端传来的数据：" + buf.toString(Charset.forName("utf-8")));
    }
}
